<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <h3 class=""> 基础信息 </h3>
    <el-form
      class="-mb-15px"
      :inline="true"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="渠道代码" prop="channelCode">
        <el-input class="!w-240px" v-model="formData.channelCode" placeholder="请输入渠道代码" />
      </el-form-item>
      <el-form-item label="保单号" prop="policyNum">
        <el-input class="!w-240px" v-model="formData.policyNum" placeholder="请输入保单号" />
      </el-form-item>
      <el-form-item label="车牌号" prop="vin">
        <el-input class="!w-240px" v-model="formData.vin" placeholder="请输入vin" />
      </el-form-item>
      <el-form-item label="VIN" prop="ownerId">
        <el-input class="!w-240px" v-model="formData.ownerId" placeholder="请输入车主id" />
      </el-form-item>
      <el-form-item label="销售车型" prop="amVehicleName">
        <el-input class="!w-240px" v-model="formData.amVehicleName" placeholder="请输入销售车型" />
      </el-form-item>
      <el-form-item label="车主姓名" prop="ownerName">
        <el-input class="!w-240px" v-model="formData.ownerName" placeholder="请输入车主姓名" />
      </el-form-item>
      <el-form-item label="车主电话" prop="ownerPhone">
        <el-input class="!w-240px" v-model="formData.ownerPhone" placeholder="请输入车主电话" />
      </el-form-item>
      <el-form-item label="车主地址" prop="ownerAddress">
        <el-input class="!w-240px" v-model="formData.ownerAddress" placeholder="请输入车主地址" />
      </el-form-item>
      <el-form-item label="保单生效日期" prop="effectDate">
        <el-date-picker
          class="!w-240px"
          v-model="formData.effectDate"
          type="date"
          value-format="x"
          placeholder="选择保单生效日期"
        />
      </el-form-item>
      <el-form-item label="保单截止日期" prop="cutDate">
        <el-date-picker
          class="!w-240px"
          v-model="formData.cutDate"
          type="date"
          value-format="x"
          placeholder="选择保单截止日期"
        />
      </el-form-item>
    </el-form>
    <h3 v-if="!formLoading" class=""> 报修信息 </h3>
    <el-form
      class="-mb-15px"
      :inline="true"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-if="!formLoading"
    >
      <el-form-item label="安装次数" prop="installNum">
        <el-input class="!w-240px" v-model="formData.installNum" placeholder="请输入安装次数" />
      </el-form-item>
      <el-form-item label="安装详情" prop="installInfo">
        <el-input class="!w-240px" v-model="formData.installInfo" placeholder="请输入安装详情" />
      </el-form-item>
      <el-form-item>
        <el-popover placement="top" width="800" trigger="click">
          <template #reference>
            <el-button @click="getHistory">查看历史记录</el-button>
          </template>
          <el-table :data="historyList">
            <el-table-column type="index" width="100" :index="indexMethod" label="报修次数" />
            <el-table-column width="300" prop="reportInfo" label="报修信息" />
            <el-table-column
              width="300"
              prop="reportDate"
              :formatter="dateFormatter"
              label="报修时间"
            />
            <el-table-column width="100" prop="auditResult" label="报修结果" />
          </el-table>
        </el-popover>
      </el-form-item>
      <el-divider />
      <el-form-item label="报案时间" prop="reportDate">
        <el-date-picker
          class="!w-240px"
          v-model="formData.reportDate"
          type="date"
          value-format="x"
          placeholder="选择报案时间"
        />
      </el-form-item>
      <el-form-item label="报案号" prop="reportNum">
        <el-input class="!w-240px" v-model="formData.reportNum" placeholder="请输入报案号" />
      </el-form-item>
      <el-form-item label="报案地址" prop="reportAddress">
        <el-input class="!w-240px" v-model="formData.reportAddress" placeholder="请输入报案地址" />
      </el-form-item>
      <el-form-item label="报案详情" prop="reportInfo">
        <el-input class="!w-600px" v-model="formData.reportInfo" placeholder="请输入报案详情" />
      </el-form-item>
      <el-form-item label="受损部位" prop="damagedPart">
        <div style="display: flex; width: 800px">
          <div style="margin-right: 10px" v-for="(item, index) in photoList" :key="index"
            ><img style="width: 100px" :src="item" alt=""
          /></div>
        </div>
      </el-form-item>
      <el-form-item label="参考损失" prop="consult">
        <el-input class="!w-240px" v-model="formData.consult" placeholder="请输入参考损失" />
      </el-form-item>
    </el-form>
    <h3 v-if="!formLoading && startExamine" class=""> 审核结果 </h3>
    <el-form
      class="-mb-15px"
      :inline="true"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-if="!formLoading && startExamine"
    >
      <el-form-item label="审核结果" prop="auditResult">
        <el-input class="!w-240px" v-model="formData.auditResult" placeholder="请输入审核结果" />
      </el-form-item>
      <el-form-item v-if="startRefuse" label="驳回原因" prop="reason">
        <el-input class="!w-400px" v-model="formData.reason" placeholder="请输入驳回原因" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div v-if="formType === 'examine'">
        <el-button v-if="!startExamine" @click="handleStartExamine" type="primary">审批</el-button>
        <el-button v-if="startExamine && !startRefuse" @click="handleStartRefusee" type="primary"
          >审批驳回</el-button
        >
        <el-button
          v-if="startExamine && !startRefuse"
          @click="() => handleExamine(1)"
          type="primary"
          >审批通过</el-button
        >
        <el-button v-if="startExamine && startRefuse" @click="() => handleExamine(2)" type="primary"
          >确定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
      <div v-else>
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OwnerItemApi, OwnerItemVO } from '@/api/channels/owneritem'
import { dateFormatter } from '@/utils/formatTime'

/** 车主报案信息 表单 */
defineOptions({ name: 'OwnerItemForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  ownerId: '',
  reportDate: '',
  reportNum: '',
  reportAddress: '',
  reportInfo: '',
  damagedPart: '',
  consult: '',
  status: '',
  installNum: '',
  installInfo: '',
  auditResult: '',
  reason: '',
  auditId: '',
  createTime: '',
  channelCode: '',
  policyNum: '',
  plateNum: '',
  vin: '',
  amVehicleId: '',
  amVehicleName: '',
  ownerName: '',
  ownerPhone: '',
  ownerAddress: '',
  policyDate: '',
  effectDate: '',
  cutDate: '',
  frontImg: '',
  tailImg: '',
  leftImg: '',
  rightImg: '',
  frontPlace: ''
})
const photoList = ref([])
const formRules = reactive({
  //ownerId: [{ required: true, message: '车主id不能为空', trigger: 'blur' }],
  // reportNum: [{ required: true, message: '报案号不能为空', trigger: 'blur' }]
})
const historyList = ref([])
const startExamine = ref(false)
const startRefuse = ref(false)
const formRef = ref() // 表单 Ref
const indexMethod = (number) => number + 1

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await OwnerItemApi.getOwnerItem(id)
      formData.value = data
      photoList.value = [
        data.frontImg,
        data.frontPlace,
        data.leftImg,
        data.rightImg,
        data.tailImg
      ].filter((item) => item)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OwnerItemVO
    if (formType.value === 'create') {
      await OwnerItemApi.createOwnerItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await OwnerItemApi.updateOwnerItem(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const getHistory = async () => {
  const data = await OwnerItemApi.getHistory({
    id: formData.value.id,
    ownerId: formData.value.ownerId
  })

  historyList.value = data
}
const handleStartExamine = () => {
  startExamine.value = true
}
const handleStartRefusee = () => {
  startRefuse.value = true
}
const handleExamine = async (status) => {
  await OwnerItemApi.updateState({
    id: formData.value.id,
    auditResult: formData.value.auditResult,
    reason: formData.value.reason,
    status
  })
  message.success('审核成功')
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ownerId: '',
    reportDate: '',
    reportNum: '',
    reportAddress: '',
    reportInfo: '',
    damagedPart: '',
    consult: '',
    status: '',
    installNum: '',
    installInfo: '',
    auditResult: '',
    reason: '',
    auditId: '',
    createTime: '',
    channelCode: '',
    policyNum: '',
    plateNum: '',
    vin: '',
    amVehicleId: '',
    amVehicleName: '',
    ownerName: '',
    ownerPhone: '',
    ownerAddress: '',
    policyDate: '',
    effectDate: '',
    cutDate: '',
    frontImg: '',
    tailImg: '',
    leftImg: '',
    rightImg: '',
    frontPlace: ''
  }
  formRef.value?.resetFields()
  startExamine.value = false
  startRefuse.value = false
}
</script>
